package service

import (
	"github.com/golang/protobuf/proto"
	"leaf/core/conf"
	"leaf/core/gate"
	"leaf/core/log"
	msg2 "leaf/core/msg"
	"leaf/core/service"
	"reflect"

	//. "leaf/core/tool"
	//"github.com/golang/protobuf/proto"
	"leaf/pb"
)

type LogicService struct {
	*service.Service
}

func NewLogicService(name string) *LogicService {
	s := &LogicService{
		Service: service.NewService(1),
	}
	//s.SetServiceName(name)
	return s
}

func (this *LogicService) Rpc_GetGateAddr(req *pb.S2C_Empty) (*pb.S2C_GateAddr, error) {
	resp := &pb.S2C_GateAddr{
		Addr: proto.String(conf.Config.WSAddr),
	}
	return resp, nil
}

func (this *LogicService) Rpc_SendNotify(requst *pb.C2S_NotifyMsg) error {
	log.Release("Rpc_SendNotify...")
	gid := requst.GetGid()
	if gid == 0 {
		log.Error("Rpc_SendNotify err:gid is zero", "gid is zero")
		return nil
	}

	msgBytes := requst.GetMsg()
	if msgBytes == nil {
		log.Error("Rpc_SendNotify gid:%v err:msgBytes is nil", msgBytes)
		return nil
	}

	msgId := requst.GetMsgId()
	msgType := msg2.GetMessageType(uint16(msgId))
	msg := reflect.New(msgType.Elem()).Interface().(proto.Message)
	if err := proto.Unmarshal(msgBytes, msg); err != nil {
		log.Error("Rpc_SendNotify gid:%v err:%v", msgBytes, err)
		return nil
	}

	agent := gate.GetAgent(gid)
	if agent == nil {
		log.Error("Rpc_SendNotify gid:%v err:agent not find", gid)
		return nil
	}
	agent.SendMsg(msg)
	log.Release("Rpc_SendNotify success")
	return nil
}
